package com.thundersoft.phonecontact.callFragments;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.thundersoft.phonecontact.CallItem;
import com.thundersoft.phonecontact.CallItemActivity;
import com.thundersoft.phonecontact.MyFunction;
import com.thundersoft.phonecontact.R;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Pixel on 2017/3/25.
 */

public class CallListFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";
    private static final String TAG = "CallListFragment";
    private SimpleDateFormat sdf;

    private RecyclerView callAllRecyclerView;
    private CallListAdapter callAllAdapter;

    private List<CallItem> listsAll=null;
    private List<CallItem> listsMissed=null;
    private List<CallItem> listsReceived=null;

    private static int number = 0;

    public CallListFragment() {
        super();
        Log.i(TAG, "CallListFragment: " + (number++));
    }

    /*
            0:所有通讯记录
            1:未接来电
            2:已接来电
             */
    public static CallListFragment newInstance(int sectionNumber) {
        CallListFragment fragment = new CallListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.call_list, container, false);
        callAllRecyclerView = (RecyclerView) rootView.findViewById(R.id.call_all_recyclerView);
        callAllRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        CallItem.updateList(getActivity().getContentResolver());
        listsAll=CallItem.getLists(0);
        listsMissed=CallItem.getLists(1);
        listsReceived=CallItem.getLists(2);
        /*
        根据getArguments().getInt(String tag)选择需要显示的列表
        0:所有通讯记录
        1:未接来电
        2:已接来电
         */
        if (callAllAdapter == null) {
            switch (getArguments().getInt(ARG_SECTION_NUMBER)){
                case 0:
                    callAllAdapter = new CallListAdapter(listsAll);
                    break;
                case 1:
                    callAllAdapter=new CallListAdapter(listsMissed);
                    break;
                case 2:
                    callAllAdapter=new CallListAdapter(listsReceived);
                    break;
                default:
                    break;
            }
        }
        callAllRecyclerView.setAdapter(callAllAdapter);
        return rootView;
    }

    private void updateUI(/*int myTag*/) {
        CallItem.updateList(getActivity().getContentResolver());
        callAllAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: running");
        updateUI();
    }

    private class CallListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private TextView callNumberTV;
        private TextView callTimeTV;
        private TextView callTypeTV;
        private TextView callNameTV;
        private CallItem callItem;

        public CallListViewHolder(View itemView) {
            super(itemView);
            callNumberTV = (TextView) itemView.findViewById(R.id.call_number_text_view);
            callTimeTV = (TextView) itemView.findViewById(R.id.call_time_text_view);
            callTypeTV = (TextView) itemView.findViewById(R.id.call_type_text_view);
            callNameTV = (TextView) itemView.findViewById(R.id.call_name_text_view);
            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);
        }

        public void bindCallItem(CallItem callItem) {
            this.callItem = callItem;
            callTimeTV.setText(dateFormat(callItem.getCallTime() + ""));
            callTypeTV.setText(callItem.getCallType());
            if (callItem.getCachedName()==null){
                callNameTV.setText(callItem.getCallNumber());
                callNumberTV.setText("");
            }
            else {
                callNameTV.setText(callItem.getCachedName());
                callNumberTV.setText(callItem.getCallNumber());
            }

            switch (callItem.getCallType()) {
                case "missed":
                    callTypeTV.setTextColor(Color.RED);
                    callTypeTV.setText(getString(R.string.tag_missed));
                    break;
                case "incoming":
                    callTypeTV.setTextColor(Color.GREEN);
                    callTypeTV.setText(getString(R.string.tag_incoming));
                    break;
                case "outgoing":
                    callTypeTV.setTextColor(Color.BLUE);
                    callTypeTV.setText(getString(R.string.tag_outgoing));
                    break;
                default:
                    callTypeTV.setTextColor(Color.BLACK);
                    callTypeTV.setText(getString(R.string.tag_rejected));
            }
        }

        public String dateFormat(String rawDate) {
            if (sdf == null) {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            }
            Date callDate = new Date(Long.parseLong(rawDate));
            return sdf.format(callDate);
        }

        @Override
        public void onClick(View v) {

            Intent intent=new Intent(getActivity(), CallItemActivity.class);
            intent.putExtra("key",callItem);
            startActivity(intent);
        }

        @Override
        public boolean onLongClick(View v) {
            new AlertDialog.Builder(getActivity())
                    .setTitle(getResources().getString(R.string.dialog_title_choose))
                    .setPositiveButton(getResources().getString(R.string.dialog_delete), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //确认删除
                            CallItem.deleteItem(getActivity().getContentResolver(), callItem.getCallTime());
                            updateUI();
                            Toast.makeText(getActivity(),"删除成功",Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNegativeButton(getResources().getString(R.string.dialog_share), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent shareIntent= MyFunction.getShareIntent();
                            shareIntent.setType("text/plain");
                            if (callItem.getCachedName()==null){
                                shareIntent.putExtra(Intent.EXTRA_TEXT,"未存储联系人\n"+callItem.getCallNumber());
                            }else {
                                shareIntent.putExtra(Intent.EXTRA_TEXT,callItem.getCachedName()+"\n"+callItem.getCallNumber());
                            }
                            startActivity(shareIntent);
                        }
                    })
                    .create()
                    .show();
            return false;
        }


    }

    private class CallListAdapter extends RecyclerView.Adapter<CallListViewHolder> {

        private List<CallItem> callItemList;


        public CallListAdapter(List<CallItem> list) {
                    callItemList = list;
            }

        @Override
        public CallListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            View view = layoutInflater.inflate(R.layout.call_item, parent, false);
            return new CallListViewHolder(view);
        }

        @Override
        public void onBindViewHolder(CallListViewHolder holder, int position) {
            CallItem callItem = callItemList.get(position);
            holder.bindCallItem(callItem);
        }

        @Override
        public int getItemCount() {
            return callItemList.size();
        }
    }

}